package com.yl.androidutilscenter.base.activity

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.yl.androidutilscenter.base.BaseViewModel
import com.yl.androidutilscenter.utils.ext.getVmClazz

/**
 * @author
 * @description: BaseVmActivity,内置viewModel
 * @date :2024/3/8
 * @version 1.0.0
 */
abstract class BaseVmActivity<VM : BaseViewModel> : BaseActivity() {

    val mViewModel: VM by lazy { createViewModel() }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val contentView = initDataBind()
        if (contentView == null) {
            setContentView(layoutId())
        } else {
            setContentView(contentView)
        }
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel.isShowLoading.observe(this) {
            if (it) {
                showLoading()
            } else {
                hideLoading()
            }
        }
        initViews(savedInstanceState)
        createObserver()
    }


    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this)[getVmClazz(this)]
    }

    /**
     * 设置布局id
     */
    abstract fun layoutId(): Int

    /**
     * 初始化views
     */
    abstract fun initViews(savedInstanceState: Bundle?)

    /**
     * 创建LiveData数据观察者
     */
    abstract fun createObserver()

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind(): View? {
        return null
    }

}